# -*- coding: utf-8 -*-
# @Time    : 2024/5/23 13:23
# @Author  : Alvin
# @File    : user_service.py

from ..utils.db_service import get_db

def check_user_password(username, password):
    db = get_db()
    # 查询用户信息
    user = db.fetchone("SELECT * FROM users WHERE username = %s", (username,))
    if user:
        # 如果用户存在，检查密码是否正确
        if user['password'] == password:
            return 'success', user
        else:
            return 'password_error', None
    else:
        return 'user_not_found', None


def create_user(username, password, email=None, nickname=None):
    db = get_db()

    # 检查用户名是否已存在
    existing_user = db.fetchone("SELECT * FROM users WHERE username = %s", (username,))
    if existing_user:
        return False, "Username already exists"

    # 创建新用户
    try:
        user_data = {
            'username': username,
            'password': password,
            'email': email,
            'nickname': nickname
        }
        db.insert_one('users', user_data)
        return True, "User created successfully"
    except Exception as e:
        return False, f"Error creating user: {str(e)}"

def update_user_info(user_id, update_data):
    db = get_db()
    try:
        rows_affected = db.update('users', update_data, 'id = %s', (user_id,))
        if rows_affected:
            return True, "User information updated successfully"
        else:
            return False, "No user found with the given ID"
    except Exception as e:
        return False, f"Error updating user information: {str(e)}"